<?php

/**
 * Name: 值班管理服务层
 * User: Silent
 * Date: 2025-11-07
 * Time: 16:00:00
 */

namespace App\Services\Checkin;

use App\Repositories\Checkin\DutyLeaderRepository;
use App\Repositories\Checkin\DutySupervisorRepository;
use App\Repositories\Config\EmployeeRepository;
use App\Services\BaseService;
use App\Services\Checkin\NotificationService;
use Illuminate\Support\Facades\DB;
use Exception;

class DutyService extends BaseService
{
    protected $dutyLeaderRepository;
    protected $dutySupervisorRepository;
    protected $employeeRepository;
    protected $notificationService;

    public function __construct(
        DutyLeaderRepository $dutyLeaderRepository,
        DutySupervisorRepository $dutySupervisorRepository,
        EmployeeRepository $employeeRepository,
        NotificationService $notificationService
    ) {
        $this->dutyLeaderRepository = $dutyLeaderRepository;
        $this->dutySupervisorRepository = $dutySupervisorRepository;
        $this->employeeRepository = $employeeRepository;
        $this->notificationService = $notificationService;
    }

    /**
     * 设置当班班长
     */
    public function setDutyLeader($dutyData, $date = null)
    {
        try {
            DB::beginTransaction();

            $date = $date ?: today();
            $results = [];

            // 处理单个或批量设置
            if (isset($dutyData['leader_id'])) {
                // 单个设置
                $results[] = $this->setSingleDutyLeader($dutyData, $date);
            } else {
                // 批量设置
                foreach ($dutyData as $item) {
                    $results[] = $this->setSingleDutyLeader($item, $date);
                }
            }

            DB::commit();

            return [
                'success' => true,
                'data' => $results,
                'message' => '当班班长设置成功'
            ];

        } catch (Exception $e) {
            DB::rollBack();

            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 设置单个当班班长
     */
    private function setSingleDutyLeader($dutyData, $date)
    {
        // 获取班长信息
        $leader = $this->employeeRepository->find($dutyData['leader_id']);
        if (!$leader) {
            throw new Exception('班长不存在');
        }

        // // 验证是否为班长级别
        // if (!$this->isLeaderPosition($leader->position)) {
        //     throw new Exception($leader->name . ' 不是班长职位，无法设置为当班班长');
        // }

        // 设置当班班长
        $dutyLeader = $this->dutyLeaderRepository->setDutyLeader(
            $leader->toArray(),
            $dutyData['team_name'] ?? $leader->team,
            $date
        );

        // 发送微信提醒
        $sendResult = $this->notificationService->sendDutyLeaderNotification($dutyLeader);

        // 如果发送成功，标记为已通知
        if ($sendResult) {
            $this->dutyLeaderRepository->markAsNotified($dutyLeader->id);
            // 重新加载数据以获取更新后的字段
            $dutyLeader->refresh();
        }

        return $dutyLeader;
    }

    /**
     * 设置值班领导
     */
    public function setDutySupervisor($dutyData, $date = null)
    {
        try {
            DB::beginTransaction();

            $date = $date ?: today();

            // 获取领导信息
            $supervisor = $this->employeeRepository->find($dutyData['supervisor_id']);
            if (!$supervisor) {
                throw new Exception('领导不存在');
            }

            // 验证是否为主管级别
            if (!$this->isSupervisorPosition($supervisor->position)) {
                throw new Exception($supervisor->name . ' 不是主管职位，无法设置为值班领导');
            }

            // 设置值班领导
            $dutySupervisor = $this->dutySupervisorRepository->setDutySupervisor(
                $supervisor->toArray(),
                $dutyData,
                $date
            );

            // 发送微信提醒
            $sendResult = $this->notificationService->sendDutySupervisorNotification($dutySupervisor);

            // 如果发送成功，标记为已通知
            if ($sendResult) {
                $this->dutySupervisorRepository->markAsNotified($dutySupervisor->id);
                // 重新加载数据以获取更新后的字段
                $dutySupervisor->refresh();
            }

            DB::commit();

            return [
                'success' => true,
                'data' => $dutySupervisor,
                'message' => '值班领导设置成功'
            ];

        } catch (Exception $e) {
            DB::rollBack();

            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取当班班长列表
     */
    public function getDutyLeadersList($date = null, $perPage = 15, $filters = [])
    {
        try {
            if ($date) {
                // 获取指定日期的当班班长
                $dutyLeaders = $this->dutyLeaderRepository->getDutyLeadersByDate($date);
                return [
                    'success' => true,
                    'data' => [
                        'date' => $date,
                        'duty_leaders' => $dutyLeaders
                    ]
                ];
            } else {
                // 获取分页列表
                $dutyLeaders = $this->dutyLeaderRepository->getDutyLeadersList($perPage, $filters);
                return [
                    'success' => true,
                    'data' => $dutyLeaders
                ];
            }

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取值班领导列表
     */
    public function getDutySupervisorsList($date = null, $perPage = 15, $filters = [])
    {
        try {
            if ($date) {
                // 获取指定日期的值班领导
                $dutySupervisor = $this->dutySupervisorRepository->getDutySupervisorByDate($date);
                return [
                    'success' => true,
                    'data' => [
                        'date' => $date,
                        'duty_supervisor' => $dutySupervisor
                    ]
                ];
            } else {
                // 获取分页列表
                $dutySupervisors = $this->dutySupervisorRepository->getDutySupervisorsList($perPage, $filters);
                return [
                    'success' => true,
                    'data' => $dutySupervisors
                ];
            }

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取可选班长列表
     * 除了部长、副部长、主管以外其他人都可以选择，仅限用户所在班组
     */
    public function getAvailableLeaders($currentUser = null, $teamName = null)
    {
        try {
            $query = $this->employeeRepository->query();

            // 排除部长、副部长、主管
            $query->whereNotIn('position', ['部长', '副部长', '主管']);

            // 如果有当前用户，优先使用用户的班组
            if ($currentUser && !empty($currentUser->team)) {
                $query->where('team', $currentUser->team);
            } elseif ($teamName) {
                // 如果没有当前用户但指定了班组，则筛选该班组
                $query->where('team', $teamName);
            }

            $leaders = $query->select('id', 'name', 'team', 'position')
                            ->orderBy('team')
                            ->orderBy('name')
                            ->get();

            return [
                'success' => true,
                'data' => $leaders
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 获取可选主管列表
     */
    public function getAvailableSupervisors()
    {
        try {
            $supervisors = $this->employeeRepository->query()
                ->whereIn('position', ['主管', '部长', '副部长'])
                ->select('id', 'name', 'team', 'position', 'phone')
                ->orderBy('position')
                ->orderBy('name')
                ->get();

            return [
                'success' => true,
                'data' => $supervisors
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 自动生成下一个工作日的当班班长
     */
    public function autoGenerateNextWorkday()
    {
        try {
            $results = $this->dutyLeaderRepository->autoGenerateNextWorkday();

            // 发送通知
            foreach ($results as $dutyLeader) {
                $sendResult = $this->notificationService->sendDutyLeaderNotification($dutyLeader);

                // 如果发送成功，标记为已通知
                if ($sendResult) {
                    $this->dutyLeaderRepository->markAsNotified($dutyLeader->id);
                }
            }

            return [
                'success' => true,
                'data' => $results,
                'message' => '自动生成下一个工作日当班班长成功'
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 检查是否为班长职位
     * 注意：副班长不属于班长职位，只有班长、组长才有 leader 权限
     */
    private function isLeaderPosition($position)
    {
        $leaderPositions = ['班长', '组长'];
        return in_array($position, $leaderPositions);
    }

    /**
     * 检查是否为主管职位
     */
    private function isSupervisorPosition($position)
    {
        $supervisorPositions = ['主管', '部长', '经理', '副主管', '副部长'];
        return in_array($position, $supervisorPositions);
    }

    /**
     * 获取当天值班信息汇总
     */
    public function getTodayDutyInfo()
    {
        try {
            $today = today();

            $dutyLeaders = $this->dutyLeaderRepository->getDutyLeadersByDate($today);
            $dutySupervisor = $this->dutySupervisorRepository->getDutySupervisorByDate($today);

            return [
                'success' => true,
                'data' => [
                    'date' => $today->format('Y-m-d'),
                    'duty_leaders' => $dutyLeaders,
                    'duty_supervisor' => $dutySupervisor
                ]
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }

    /**
     * 根据值班人员id获取详情信息
     */
    public function getSupervisorDetail($supervisorId)
    {
        try {
            // 验证 supervisor_id 是否存在
            $employee = $this->employeeRepository->find($supervisorId);
            if (!$employee) {
                return [
                    'success' => false,
                    'message' => '值班人员不存在'
                ];
            }

            // 获取值班人员详情
            $detail = $this->dutySupervisorRepository->getSupervisorDetailById($supervisorId);

            // 如果没有值班记录，返回基本信息
            if (!$detail['supervisor_info']) {
                $detail['supervisor_info'] = [
                    'id' => $employee->id,
                    'name' => $employee->name,
                    'phone' => $employee->phone ?? '',
                    'team' => $employee->team ?? '',
                    'position' => $employee->position ?? '',
                ];
            }

            return [
                'success' => true,
                'data' => $detail
            ];

        } catch (Exception $e) {
            return [
                'success' => false,
                'message' => $e->getMessage()
            ];
        }
    }
}

